package nckd.wnqjt.tmc.tda.plugin.form;

import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import kd.bos.ai.util.JsonUtil;
import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.AppInfo;
import kd.bos.entity.AppMetadataCache;
import kd.bos.entity.qing.*;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.form.IFormView;
import kd.bos.form.IPageCache;
import kd.bos.form.ShowType;
import kd.bos.form.control.IQingAnalysis;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.mvc.SessionManager;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.report.ReportShowParameter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

/**
 * @author husheng
 * @date 2024-11-04 11:55
 * @description 动态表单插件      按银行大类分布
 */
public class CreditlimitBankcateQingDataProvider extends AbstractFormPlugin implements IQingDataProvider {
    /**
     * 定义轻分析表头
     */
    @Override
    public QingMeta getMeta(String s) {
        String entityKey = "cfm_creditlimit";
        QingMeta meta = new QingMeta();
        EntryEntity entity = new EntryEntity();
        entity.setKey(entityKey);
        entity.setName(new LocaleString("PK"));
        entity.setPkFieldName("id");
        meta.addEntryEntity(entity);

        Field column = new Field();
        column.setEntity(entityKey);//字段所属实体key	否
        column.setKey("id");// 字段名(唯一标识)	是
        column.setFieldType(QingFieldType.Int.toNumber()); //数据类型	是
        column.setName(new LocaleString("id")); //字段别名	是
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("orgName");
        column.setFieldType(QingFieldType.String.toNumber());
        column.setName(new LocaleString("授信主体"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("totalamt");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("授信总额"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("useamt");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("已用额度"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("residual_credit");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("剩余额度"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("bank_cate_name");
        column.setFieldType(QingFieldType.String.toNumber());
        column.setName(new LocaleString("银行大类"));
        meta.addColumn(column);

        return meta;
    }

    /**
     * 获取轻分析数据，通过拿到过滤条件可以重新定义取数逻辑
     */
    @Override
    public QingData getData(String s, int i, int i1) {
        //拿过滤条件，进行取数
        String qFilter = getPageCache().get("qFilter");
        if (qFilter != null) {
            //通过此方法拿到过滤参数
            Map<String, Object> filterParam = (Map) JSON.parseObject(qFilter, Map.class);
        }

        // 授信额度管理
        String creditlimitSql = "id,number,org,org.name orgName,org.number orgNumber,totalamt,useamt,avaramt,bank,(totalamt - useamt) residual_credit";
        QFilter filter = new QFilter("status", QCP.equals, "C")
                .and("enddate", QCP.large_than, this.getCurrentDate())
                .and("isclose", QCP.not_equals, "1");
        DataSet cfmCreditlimit = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cfm_creditlimit", creditlimitSql, filter.toArray(), null);

        // 合作金融机构
        //构建合作金融机构过滤条件 20250810 dsx添加
        QFilter finOrgInfoQFilter = new QFilter("enable", QCP.equals, "1").and(new QFilter("status", QCP.equals, "C"));
        DataSet bdFinorginfo = QueryServiceHelper.queryDataSet(this.getClass().getName(), "bd_finorginfo", "id,bank_cate,bank_cate.name bank_cate_name", finOrgInfoQFilter.toArray(), null);

        DataSet dataSet = cfmCreditlimit.join(bdFinorginfo).on("bank", "id")
                .select(cfmCreditlimit.getRowMeta().getFieldNames(), new String[]{"bank_cate_name"}).finish();

        DynamicObject test1 = BusinessDataServiceHelper.newDynamicObject("nckd_testdocuments");
        test1.set("billno", "test-creditlimit7-" + new SimpleDateFormat("yyyyMMddHHmm").format(new Date()));
        test1.set("billstatus", "A");
        DynamicObjectCollection entryentity1 = test1.getDynamicObjectCollection("entryentity");
        //打印单据
        DataSet recCopy1 = dataSet.copy();
        while (recCopy1.hasNext()) {
            DynamicObject entry = entryentity1.addNew();
            Row row = recCopy1.next();
            entry.set("nckd_name", "按银行大类分布(已用额度)");
            entry.set("nckd_number", row.get("number"));
            entry.set("nckd_amount", row.get("useamt"));
        }
        SaveServiceHelper.save(new DynamicObject[]{test1});

        DynamicObject test2 = BusinessDataServiceHelper.newDynamicObject("nckd_testdocuments");
        test2.set("billno", "test-creditlimit8-" + new SimpleDateFormat("yyyyMMddHHmm").format(new Date()));
        test2.set("billstatus", "A");
        DynamicObjectCollection entryentity2 = test2.getDynamicObjectCollection("entryentity");
        //打印单据
        DataSet recCopy2 = dataSet.copy();
        while (recCopy2.hasNext()) {
            DynamicObject entry = entryentity2.addNew();
            Row row = recCopy2.next();
            entry.set("nckd_name", "按银行大类分布(剩余额度)");
            entry.set("nckd_number", row.get("number"));
            entry.set("nckd_amount", row.get("residual_credit"));
        }
        SaveServiceHelper.save(new DynamicObject[]{test2});

        QingData data = null;
        if (i < 200) {
            data = new QingData();
            Map<String, Integer> dataindex = new HashMap<>();
            dataindex.put("id", 0);
            dataindex.put("orgName", 1);
            dataindex.put("totalamt", 2);
            dataindex.put("useamt", 3);
            dataindex.put("residual_credit", 4);
            dataindex.put("bank_cate_name", 5);
            data.setDataindex(dataindex);

            List<Object[]> rows = new ArrayList<>();
            while (dataSet.hasNext()) {
                Row row = dataSet.next();
                Object[] obj = new Object[6];
                obj[0] = row.getLong("id");
                obj[1] = row.getString("orgName");
                obj[2] = row.getBigDecimal("totalamt");
                obj[3] = row.getBigDecimal("useamt");
                obj[4] = row.getBigDecimal("residual_credit");
                obj[5] = row.getString("bank_cate_name");
                rows.add(obj);
            }
            data.setRows(rows);
        }

        return data;
    }

    /**
     * 获取动态表单联查信息
     *
     * @param pageId
     * @param ctrKey
     * @return
     */
    @Override
    public List<QingLinkageInfo> getLinkageInfo(String pageId, String ctrKey) {
        List<QingLinkageInfo> infos = new ArrayList<QingLinkageInfo>();
        QingLinkageInfo info = new QingLinkageInfo();
        Map<String, String> formKey = new HashMap<>();
        AppInfo appInfo = AppMetadataCache.getAppInfo("tda");
        formKey.put("AppId", appInfo.getAppId()); //需要打开的表单所在应用的id
        formKey.put("FormId", "nckd_creditguarantee"); //需要打开的表单的id
        formKey.put("System", "IERP");
        formKey.put("CtrKey", ctrKey);
        info.setFormKey(JsonUtil.encodeToString(formKey));
        info.setFormDisplayName("授信担保");//联查到表单的显示名称
        info.setFormPrimaryKey("id");//联查到表单的主键
        infos.add(info);//可以添加多个QingLinkageInfo对象
        this.getView().getPageCache().put("qingViewControlKey", ctrKey);//必要语句!
        return infos;
    }

    /**
     * <p>调用此接口，触发业务逻辑，具体业务联查实现此接口<p/>
     *
     * @param ids    轻分析得到动态表单需要联査的1d的集合
     * @param pageId
     * @param formId
     * @param appId
     */
    @Override
    public void fireLinkageInfo(List<String> ids, String pageId, String formId, String appId) {
        //IQingDataProvider.super.fireLinkageInfo(ids, pageId, formId, appId);
        /*具体的表单打开逻辑，业务自己去实现
        ids:联查到的主键的值
        pageId:触发联査的页面的pageId，可用于找到触发联査的页面: FormView view = (FormView)Sessiomanager.getCurrent().getView(pageId)
        formId:联查到的表单的id
        appId:联查到的表单所在应用的Id
        */

        /*注意: 如果需要使用芒穹的view.showForm 方式打开表单，需要添加以下代码*/
        // 组装 FormShomParaneter(披照业务场景亲实现)
        ReportShowParameter reportShowParameter = new ReportShowParameter();
        reportShowParameter.getOpenStyle().setShowType(ShowType.Modal);
        reportShowParameter.setAppId(appId);
        reportShowParameter.setFormId(formId);//报表标识
        //拿过滤条件，进行取数
        String qFilter = getPageCache().get("qFilter"); //从仪表板进去 拿不到
        //通过此方法拿到过滤参数
        Map<String, Object> filterParam = new HashMap<>();
        // 设置报表过滤条件
        ReportQueryParam reportQueryParam = new ReportQueryParam();
//        filterParam.put("id", ids);
        reportQueryParam.setCustomParam(filterParam);
        reportShowParameter.setQueryParam(reportQueryParam);

        /*******************************showForm必要的代码******************************************/
        IFormView view = SessionManager.getCurrent().getView(pageId);
        String ctrKey = this.getView().getPageCache().get("qingViewControlKey");
        if (ctrKey != null) {
            if (view.getControl(ctrKey) instanceof IQingAnalysis) {
                //设计器的场景，直接showForm
                view.showForm(reportShowParameter);
                return;
            }
        }
        //其他场景需要，返回FormShowParameter，由轻分析来 showForm
        this.getView().setClientReturnData(ListShowParameter.toJsonString(reportShowParameter));
        /*******************************showForm必要的代码******************************************/
    }

    @Override
    public void setFilterParameter(String filterParameter) {
        IPageCache pageCache = getPageCache();
        pageCache.put("qFilter", filterParameter);

    }

    @Override
    public String getFilterParameter() {
        return getPageCache().get("qFilter");
    }

    private Date getCurrentDate() {
        Calendar cal = new GregorianCalendar();
//        cal.set(11, 0);
//        cal.set(12, 0);
//        cal.set(13, 0);
//        cal.set(14, 0);
        return cal.getTime();
    }
}
